package com.sanmao.spring.demo.security.springsecurityoauth2demo.configuration;

import com.sanmao.spring.demo.security.springsecurityoauth2demo.authentication.mobile.MobileAuthenticationSecurityConfig;
import com.sanmao.spring.demo.security.springsecurityoauth2demo.handler.DmAuthenticationFailureHandler;
import com.sanmao.spring.demo.security.springsecurityoauth2demo.handler.DmAuthenticationSuccessHandler;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 认证相关配置
 * @Author: Sanmao
 * @Date: 2021/08/31/12:06
 * @Description:
 */
@Primary
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

  @Autowired
  protected DmAuthenticationSuccessHandler dmAuthenticationSuccessHandler;

  @Autowired
  protected DmAuthenticationFailureHandler dmAuthenticationFailureHandler;

  @Autowired
  private MobileAuthenticationSecurityConfig mobileAuthenticationSecurityConfig;

  @Override
  @SneakyThrows
  protected void configure(HttpSecurity http) throws Exception {
    http
      // 手机验证码登录
      .apply(mobileAuthenticationSecurityConfig)
      .and()
      .authorizeRequests()
      //手机验证码登录地址
      .antMatchers("/mobile/token", "/email/token")
      .permitAll()
      .and()
      .authorizeRequests()
      .antMatchers(
        "/register",
        "/social/**",
        "/**/*.js",
        "/**/*.css",
        "/**/*.jpg",
        "/**/*.png",
        "/**/*.woff2",
        "/code/image")
      .permitAll()//以上的请求都不需要认证
      .anyRequest()
      .authenticated()
      .and()
      .csrf().disable();
  }

  /**
   * 不拦截静态资源
   *
   * @param web
   */
  @Override
  public void configure(WebSecurity web) {
    web.ignoring().antMatchers("/css/**");
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

}
